package blog.web;

import java.util.Collection;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import blog.model.Blog;
import blog.service.BlogService;

/**
 * @author Hakdo 
 *
 */
@Controller
@SessionAttributes("blog")
public class BlogController {
	
	@Autowired private BlogService blogService;
	
	@RequestMapping(value = "/findBlogs", method = RequestMethod.GET)
	public Collection<Blog> findBlogsHandler() { 
		return blogService.findBlogs();
	}

	@RequestMapping(value= "/editBlog", method = RequestMethod.GET)
	public Blog editBlogHandler(@RequestParam("blogId") int blogId) {
		return blogService.findBlog(blogId); 
	}
	
	@RequestMapping(value= "/saveBlog", method = RequestMethod.POST)
	public String saveBlogHandler(Blog blog) {
		blogService.createBlog(blog);
		return "redirect:findBlogs.do";
	}
	
	@RequestMapping(value= "/updateBlog", method = RequestMethod.POST)
	public String updateBlogHandler(Blog blog) {
		blog.setRegDate(new Date());
		blogService.updateBlog(blog);
		return "redirect:findBlogs.do";
	}
	
	@RequestMapping(value= "/deleteBlog", method = RequestMethod.GET)
	public String deleteBlogHandler(@RequestParam("blogId") int blogId) {
		blogService.deleteBlog(blogId);
		return "redirect:findBlogs.do";
	}
	
	@RequestMapping(value= "/createBlog", method = RequestMethod.GET)
	public void createBlogHandler(Model model) {
		model.addAttribute("blog", new Blog(new Date()));
	}
	
}
